package com.xkcyy.one.executor;

import com.xkcyy.one.entity.Tool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 工具执行器工厂
 * 负责根据工具类型选择适合的执行器
 * 
 * @author yuand
 */
@Component
public class ToolExecutorFactory {

    private static final Logger logger = LoggerFactory.getLogger(ToolExecutorFactory.class);

    private final List<ToolExecutor> executors;

    @Autowired
    public ToolExecutorFactory(List<ToolExecutor> executors) {
        this.executors = executors;
    }

    /**
     * 获取支持执行指定工具的执行器
     * 
     * @param tool 工具定义
     * @return 工具执行器，如果没有支持的执行器则返回null
     */
    public ToolExecutor getExecutor(Tool tool) {
        if (tool == null) {
            return null;
        }

        for (ToolExecutor executor : executors) {
            if (executor.supports(tool)) {
                logger.debug("找到工具执行器: {}，工具: {}", executor.getClass().getSimpleName(), tool.getName());
                return executor;
            }
        }

        logger.warn("未找到支持工具[{}]的执行器，实现类型: {}", tool.getName(), tool.getImplementationType());
        return null;
    }

    /**
     * 执行工具调用
     * 
     * @param tool  工具定义
     * @param input 输入参数
     * @return 执行结果
     * @throws IllegalArgumentException 如果找不到支持的执行器或输入参数无效
     */
    public Object execute(Tool tool, Object input) {
        ToolExecutor executor = getExecutor(tool);
        if (executor == null) {
            throw new IllegalArgumentException("找不到支持的工具执行器: " + tool.getName());
        }

        try {
            // 验证输入
            executor.validateInput(tool, input);

            // 执行工具
            return executor.execute(tool, input);
        } catch (Exception e) {
            logger.error("执行工具失败: " + e.getMessage(), e);
            throw e;
        }
    }
}